const BASE_URL = import.meta.env.VITE_API_BASE_URL || '';

function requestInterceptor(config) {
  // 可在此添加token等公共头部
  config.headers = {
    ...config.headers,
    // Authorization: `Bearer ${localStorage.getItem('token')}`,
  };
  return config;
}

function responseInterceptor(response) {
  if (!response.ok) {
    return Promise.reject(response);
  }
  return response.json();
}

function fetchRequest(url, options = {}) {
  const config = requestInterceptor({
    ...options,
    headers: options.headers || {},
  });
  return fetch(BASE_URL + url, config)
    .then(responseInterceptor)
    .catch((error) => {
      // 可统一处理错误
      console.error('请求错误:', error);
      throw error;
    });
}

export const get = (url, params = {}) => {
  const query = new URLSearchParams(params).toString();
  return fetchRequest(url + (query ? `?${query}` : ''), {
    method: 'GET',
  });
};

export const post = (url, data = {}) => {
  return fetchRequest(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  });
};

export const upload = (url, file, extraData = {}) => {
  const formData = new FormData();
  formData.append('file', file);
  Object.entries(extraData).forEach(([key, value]) => {
    formData.append(key, value);
  });
  return fetchRequest(url, {
    method: 'POST',
    body: formData,
  });
};